package cn.thoughtworks.model;

/**
 * 迷宫类
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @create 2018-07-27-14:57
 */
public class Maze implements Product {

    private int row;
    private int col;
    private int[][] roads;

    public Maze(int row, int col) {
        this.row = row;
        this.col = col;
    }

    /**
     * @return 返回字符串表示方式
     */
    @Override
    public String render() {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (roads[i][j] == 0)
                    res.append("[W]");
                else if (roads[i][j] == -1) {
                    res.append("[*]");
                } else
                    res.append("[R]");
                if (j != col - 1)
                    res.append(" ");
                else
                    res.append("\n");
            }
        }

        return res.toString();
    }


    public void change(Point p) {
        this.roads[p.getX()][p.getY()] = -1;
    }


    public void move(Point p, String command) {
        int x = p.getX() * 2 + 1;
        int y = p.getY() * 2 + 1;

        char[] chars = command.toCharArray();

        for (char c : chars) {
            switch (c) {
                case 'W':
                    if(isMove(x,y,'W'))
                        y-=1;
                    break;
                case 'S':if (isMove(x,y,'S'))
                    x+=1;
                    break;
                case 'A':if (isMove(x,y,'A'))
                    x -=1;
                    break;
                case 'D':if (isMove(x,y,'D'))
                    y+=1;
                    break;
                default:
                    continue;
            }
        }

        change(new Point(x,y));
    }


    private boolean isMove(int x,int y, char direction) {
        int row = this.roads.length;
        int col = this.roads[0].length;
        switch (direction) {
            case 'D':
                if (y<col-2&&roads[x][y+1]==1)
                    return true;
                else
                    return false;
            case 'S':
                if (x<row-2&&roads[x+1][y] == 1)
                    return true;
                return false;
            case 'A':
                if (x>1&&roads[x-1][y] == 1)
                    return true;
                return false;
            case 'W':
                if (y>1&&roads[x][y-1] == 1)
                    return true;
                return false;
        }

        return false;
    }


    public void setRoads(int[][] roads) {
        this.roads = roads;
    }
}
